package com.bl.student.service.biz.teacher.impl;

import com.bl.student.common.ApiResponseCode;
import com.bl.student.common.CommonServiceException;
import com.bl.student.common.enums.PointType;
import com.bl.student.common.enums.UserStatus;
import com.bl.student.common.utils.ASE;
import com.bl.student.common.utils.Generator;
import com.bl.student.common.utils.ListUtils;
import com.bl.student.common.utils.UUIDUtils;
import com.bl.student.dao.model.PointEntity;
import com.bl.student.dao.model.TeacherEntity;
import com.bl.student.dao.model.UserEntity;
import com.bl.student.dao.redis.TeacherInfoDao;
import com.bl.student.dao.redis.UserInfoDao;
import com.bl.student.dao.redis.model.TeacherInfo;
import com.bl.student.dao.redis.model.UserInfo;
import com.bl.student.dao.repository.PointRepository;
import com.bl.student.dao.repository.TeacherRepository;
import com.bl.student.dao.repository.UserPointRepository;
import com.bl.student.service.biz.point.PointService;
import com.bl.student.service.biz.teacher.TeacherMainService;
import com.bl.student.service.biz.teacher.TeacherService;
import com.bl.student.service.biz.user.UserService;
import com.bl.student.service.vo.main.LoginResponseVo;
import com.bl.student.service.vo.teacher.TeacherInfoModifyVo;
import com.bl.student.service.vo.teacher.TeacherLoginResponseVo;
import com.bl.student.service.vo.teacher.TeacherLoginVo;
import com.bl.student.service.vo.teacher.TeacherRegisterVo;
import com.bl.student.tp.hx.user.HxUserApi;
import com.bl.student.tp.hx.user.HxUserRegisterRequest;
import com.bl.student.tp.hx.user.HxUserRegisterResponse;
import com.bl.student.tp.wechat.auth.WechatAccessTokenMiniRequest;
import com.bl.student.tp.wechat.auth.WechatAccessTokenResponse;
import com.gexin.fastjson.JSONObject;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by yujingyi on 2018/2/25.
 */
@Service
@Log4j2
public class TeacherMainServiceImpl implements TeacherMainService {

    private final String REGISTER_DUPLICATED_ACCOUNT = "该帐号已被注册";

    @Autowired
    TeacherService teacherService;

    @Autowired
    UserInfoDao userInfoDao;

    @Autowired
    UserService userService;

    @Autowired
    HxUserApi hxUserApi;

    @Autowired
    TeacherRepository teacherRepository;

    @Autowired
    PointService pointService;

    @Autowired
    PointRepository pointRepository;

    @Override
    public TeacherLoginResponseVo appLogin(TeacherLoginVo teacherLoginVo) {
        TeacherEntity teacherEntity = fetchAvailableUser(teacherLoginVo.getMobile(), teacherLoginVo.getPassword());

        String token = Generator.generateToken(teacherEntity.getId(), teacherEntity.getAccount(), teacherEntity.getPassword());

        UserInfo teacherInfo = new UserInfo();
        teacherInfo.setId(teacherEntity.getId());
        teacherInfo.setType("PARTYA");
        teacherInfo.setMobile(teacherEntity.getMobile());
        teacherInfo.setAccount(teacherEntity.getAccount());
        teacherInfo.setHxId(teacherEntity.getHxId());

        userInfoDao.setUserInfo(teacherInfo);

        TeacherLoginResponseVo loginResponseVo;
        loginResponseVo = TeacherLoginResponseVo.builder()
                .mobile(teacherEntity.getMobile())
                .name(teacherEntity.getNickname())
                .token(token)
                .hxName(teacherEntity.getHxName())
                .type("PARTYA")
                .hxId(teacherEntity.getHxId())
                .avatar(teacherEntity.getAvatar())
                .openId(teacherEntity.getOpenId())
                .id(teacherEntity.getId())
                .build();

        return loginResponseVo;
    }

    private TeacherEntity fetchAvailableUser(String account, String password) {
        TeacherEntity teacherEntity = teacherService.getTeacherByMobile(account);

        if (teacherEntity == null) {
            throw new CommonServiceException(ApiResponseCode.USER_NOT_EXIST.getCode(), ApiResponseCode.USER_NOT_EXIST.getMsg());
        }

        if (!teacherEntity.getPassword().equals(password)) {
            throw new CommonServiceException(ApiResponseCode.PASSWORD_WRONG.getCode(), ApiResponseCode.PASSWORD_WRONG.getMsg());
        }

        if (teacherEntity.getStatus() == UserStatus.LOCKED) {
            throw new CommonServiceException(ApiResponseCode.USER_LOCKED.getCode(), ApiResponseCode.USER_LOCKED.getMsg());
        }
        return teacherEntity;
    }

    @Override
    public void logout(UserInfo userInfo) {
        userInfoDao.delUserInfo(userInfo.getAccount());
    }

    @Override
    public LoginResponseVo register(TeacherRegisterVo teacherRegisterVo, String openId, String hxId) {

        if (teacherRegisterVo.getMobile() == null) {
            throw new CommonServiceException(ApiResponseCode.DATA_EXISTED.getCode(), "手机号不能为空");
        }

//        // register hx
//        HxUserRegisterRequest hxUserRegisterRequest = HxUserRegisterRequest.builder()
//                .nickname(teacherRegisterVo.getName())
//                .password(teacherRegisterVo.getPassword())
//                .username(teacherRegisterVo.getAccount())
//                .build();
//
//        Optional<HxUserRegisterResponse> hxUserRegisterResponseOptional = hxUserApi.register(hxUserRegisterRequest);
//
//        // request failed
//        if (!hxUserRegisterResponseOptional.isPresent()) {
//            throw new CommonServiceException(ApiResponseCode.HX_REQUEST_FAILED.getCode(), ApiResponseCode.HX_REQUEST_FAILED.getMsg());
//        }
//
//        HxUserRegisterResponse hxUserRegisterResponse = hxUserRegisterResponseOptional.get();
//        String hxId = hxUserRegisterResponse.getEntities().get(0).getUuid();

        List<TeacherEntity> teacherEntityList = teacherRepository.findByOpenId(openId);
        TeacherEntity teacherEntity = null;
        if (teacherEntityList != null && teacherEntityList.size() > 0) {
            teacherEntity = ListUtils.getFirst(teacherEntityList);
        }
        teacherEntity.setMobile(teacherRegisterVo.getMobile());
        teacherEntity.setHxId(teacherRegisterVo.getHxId());
        teacherEntity.setPassword(teacherRegisterVo.getPassword());
        teacherEntity.setInviteCode(teacherRegisterVo.getSelfInviteCode());
        teacherEntity.setCreateTime(new Date());
        teacherEntity.setHxName(teacherRegisterVo.getHxName());
        teacherRepository.save(teacherEntity);

        //增加注册积分
        PointEntity pointEntity0 = pointRepository.findByType("REGISTER");
        int point0 = pointEntity0.getValue();
        // 增加积分
        pointService.addPointPartyA(teacherEntity.getId(), point0);
        // 增加记录
        pointService.addTeacherPoint(teacherEntity.getId(), PointType.REGISTER, point0, "0");


//        // handle invite code
//        String inviteCode = teacherRegisterVo.getInviteCode();
//        if (!Strings.isNullOrEmpty(inviteCode)) {
//            TeacherEntity inviter = teacherService.getTeacherByInviteCode(inviteCode);
//            if (inviter != null) {
//                userService.addUserInvite(inviter.getId(), teacherEntity.getId());
//                PointEntity pointEntity = pointRepository.findByType("INVITE");
//                int point = pointEntity.getValue();
//                // 增加积分
//                pointService.addPointPartyA(inviter.getId(), point);
//                // 增加记录
//                pointService.addUserPoint(inviter.getId(), PointType.INVITE, point, "0");
//            }
//
////            if (inviter == null) {
////                throw new CommonServiceException(ApiResponseCode.DATA_EXISTED.getCode(), "邀请码填写错误");
////            }
//        }

        String token = Generator.generateToken(teacherEntity.getId(), teacherEntity.getMobile(), teacherEntity.getPassword());
        LoginResponseVo loginResponseVo;
        loginResponseVo = LoginResponseVo.builder()
                .mobile(teacherEntity.getMobile())
                .name(teacherEntity.getNickname())
                .token(token)
                .hxId(teacherEntity.getHxId())
                .hxName(teacherEntity.getHxName())
                .unionId(teacherEntity.getUnionId())
                .avatar(teacherEntity.getAvatar())
                .openId(teacherEntity.getOpenId())
                .id(teacherEntity.getId())
                .build();
        return loginResponseVo;
    }

    @Override
    public void modify(TeacherInfoModifyVo teacherInfoModifyVo, TeacherInfo teacherInfo) {
        TeacherEntity teacherEntity = teacherRepository.findOne(teacherInfo.getId());
        if (teacherEntity == null) {
            throw new CommonServiceException(ApiResponseCode.DATA_NOT_EXIST.getCode(), ApiResponseCode.DATA_NOT_EXIST.getMsg());
        }
        teacherEntity.setAvatar(teacherInfoModifyVo.getAvatar());
        teacherRepository.save(teacherEntity);
    }

    @Override
    public TeacherEntity createWechatUser(String nickname, int sex, String avatar, String openId, String unionId) {
        TeacherEntity teacherEntity = new TeacherEntity();
        String userId = UUIDUtils.getUUID();
        teacherEntity.setId(userId);
        teacherEntity.setOpenId(openId);
        teacherEntity.setUnionId(unionId);
        teacherEntity.setMobile("");
        teacherEntity.setStatus(UserStatus.NORMAL);
        teacherEntity.setCreateTime(new Date());
        teacherEntity.setUpdateTime(new Date());
        teacherEntity.setAvatar(avatar);
        teacherEntity.setNickname(openId.substring(6));
        teacherRepository.save(teacherEntity);

        return teacherEntity;
    }
}
